package com.yindian.cos.monitor.aspect;

import com.yindian.cos.monitor.core.TrackerService;
import com.yindian.cos.monitor.model.Tracker;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 监控@Async注解，自动将Tracker转接到当前线程
 *
 * @author zhangchuanhao
 * @date 2018/12/27
 */
@Aspect
@Component
@Log4j2
public class AsyncAspect {

    @Pointcut("@annotation(org.springframework.scheduling.annotation.Async)")
    private void AsyncCut() {
    }

    @Before(value = "AsyncCut()")
    public void doBefore(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            String argClassName = arg.getClass().getName();
            String trackerClassName = Tracker.class.getName();
            if (argClassName.equals(trackerClassName)) {
                Tracker tracker = (Tracker) arg;
                TrackerService.trackerStart(tracker);
            }
        }
    }

    @After(value = "AsyncCut()")
    public void doAfter(JoinPoint joinPoint) {
        TrackerService.trackerEnd();
    }
}
